package com.yunjijia.shiro;

import com.yunjijia.pojo.RolePermission;
import com.yunjijia.pojo.User;
import com.yunjijia.pojo.Userrole;
import com.yunjijia.service.*;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.crazycake.shiro.RedisSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *  身份校验核心类;
 * @author ZZ
 * @version v.0.1
 */
public class MyShiroRealm extends AuthorizingRealm {

    private final static Logger log = LoggerFactory.getLogger(AuthorizingRealm.class);

//    @Resource
//    private UserInfoService userInfoService;
    @Resource
    private IUserService iuserService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IUserroleService userroleService;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private IPermissionService permissionService;


//    @Resource
//    private RedisSessionDAO redisSessionDAO;

    /**     1
     *执行认证逻辑
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String)token.getPrincipal();
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        log.info("username:realm"+username);
        User userInfo = iuserService.findByUsername(username);
        System.out.println(userInfo);
        System.out.println("----->>userInfo="+userInfo.getUsername()+"---"+userInfo.getPassword());
        if(userInfo == null){
            return null;
        }


        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, //用户名
                userInfo.getPassword(), //密码
                getName()  //realm name
        );

        return authenticationInfo;
    }


    /**     2
     * 执行授权与逻辑
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User userinfo  = (User)principals.getPrimaryPrincipal();
//		userInfo userInfo= userInfoService.findByUsername(username);
        log.info("用户实体："+userinfo);
        String uid= userinfo.getUserid();
        List<Userrole> list=userroleService.getRolesByuid(uid);
        for(Userrole userrole:list){
            int roleid=userrole.getRoleid();
            authorizationInfo.addRole(roleService.getRoleByrid(roleid).getName());
            log.info("角色名字："+roleService.getRoleByrid(roleid).getName());
            List<RolePermission> list1=rolePermissionService.getPermissionsByroleid(roleid);
            for(RolePermission p:list1){

                authorizationInfo.addStringPermission(permissionService.getPermissionByid(p.getPermissionid()).getUrl());
                log.info("权限名字："+permissionService.getPermissionByid(p.getPermissionid()).getUrl());
//                log.info("username:realm"+username);
            }
        }



        return authorizationInfo;
    }



    /**
     * 根据userId 清除当前session存在的用户的权限缓存
     * @param userIds 已经修改了权限的userId
     */
    /*public void clearUserAuthByUserId(List<Integer> userIds){
        if(null == userIds || userIds.size() == 0)	return ;
        //获取所有session
        Collection<Session> sessions = redisSessionDAO.getActiveSessions();
        //定义返回
        List<SimplePrincipalCollection> list = new ArrayList<SimplePrincipalCollection>();
        for (Session session:sessions){
            //获取session登录信息。
            Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if(null != obj && obj instanceof SimplePrincipalCollection){
                //强转
                SimplePrincipalCollection spc = (SimplePrincipalCollection)obj;
                //判断用户，匹配用户ID。
                obj = spc.getPrimaryPrincipal();
                if(null != obj && obj instanceof User){
                    User user = (User) obj;
                    System.out.println("user:"+user);
                    //比较用户ID，符合即加入集合
                    if(null != user && userIds.contains(user.getUserid())){
                        list.add(spc);
                    }
                }
            }
        }
        RealmSecurityManager securityManager =
                (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyShiroRealm realm = (MyShiroRealm)securityManager.getRealms().iterator().next();
        for (SimplePrincipalCollection simplePrincipalCollection : list) {
            realm.clearCachedAuthorizationInfo(simplePrincipalCollection);
        }
    }*/


}